package com.reebake.ideal.security.dao;

import com.reebake.ideal.security.code.CodeAuthenticationToken;
import com.reebake.ideal.security.entity.UsernameCredential;
import com.reebake.ideal.security.handler.AuthenticationCaptchaHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;

public class UsernamePasswordAuthenticationProvider extends DaoAuthenticationProvider {
    @Autowired
    private AuthenticationCaptchaHandler authenticationCaptchaHandler;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = (UsernamePasswordAuthenticationToken) authentication;
        UsernameCredential credential = (UsernameCredential) usernamePasswordAuthenticationToken.getCredentials();
        String username = credential.getUsername();
        String password = credential.getPassword();

        authenticationCaptchaHandler.checkCaptcha(username, usernamePasswordAuthenticationToken.getCaptcha());

        Authentication authRequest = org.springframework.security.authentication.UsernamePasswordAuthenticationToken.unauthenticated(username, password);
        return super.authenticate(authRequest);
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication);
    }

}
